#! /usr/bin/env python
# -*- encoding: utf-8 -*-
#
# Copyright 2022 the deepx authors.
# Author: Chuan Cheng (chuancheng@tencent.com)
#

import os
import shutil
import subprocess
from collections import namedtuple
from textwrap import dedent

from setuptools import Command, find_packages, setup
from setuptools.command.sdist import sdist as _sdist

TOP_DIR = os.path.realpath(os.path.dirname(__file__))
SRC_DIR = TOP_DIR


# delete file by folder
def remove_files_by_folder(folder_path):
    folder_list = list()
    for folder in os.listdir(folder_path):
        folder_list.append(folder)
    for file in folder_list:
        rm_path = os.path.join(folder_path, file)
        print(rm_path)
        shutil.rmtree(rm_path)

#delete remain setup file
if os.path.exists("./build"):
    remove_files_by_folder("./build")

# try to get git_version
try:
    git_version = (
        subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=TOP_DIR)
        .decode("ascii")
        .strip()
    )
except (OSError, subprocess.CalledProcessError):
    git_version = None

# open local file version.txt
# read version
with open(os.path.join(TOP_DIR, "version.txt"), "rb") as version_file:
    VersionInfo = namedtuple(
        "VersionInfo", ["version", "git_version"]
    )(
        version=version_file.read().decode("ascii").strip(),
        git_version=git_version,
    )


# creat version for setup
class create_version(Command):
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        with open(os.path.join(SRC_DIR, "version.py"), "w") as f:
            f.write(
                dedent(
                    """\
            # This file is generated by setup.py. DO NOT EDIT!

            __version__ = '{version}'
            __git_version__ = '{git_version}'
            """.format(
                        **dict(VersionInfo._asdict())
                    )
                )
            )


class sdist(_sdist):
    def run(self):
        self.run_command("create_version")
        return _sdist.run(self)


def configure_console_scripts():
    return [
    ]

# begin setup
# checkout version.txt

setup(
    name="Auto48X",
    version=VersionInfo.version,
    description="A platform to do qat and distil",
    setup_requires=[],
    data_files=[(".", ["version.txt"])],
    packages=find_packages(),
    package_data = {
        # If any package contains *.txt or *.rst files, include them:
        '': ['*.json', '*.txt']
    },
    url="/Auto48X",
    python_requires=">=3.8",
    install_requires=[
    ],
)
